<?php
/**
 * FunctionCommon
 * - Use contain function common
 * @author RUNSYSTEM
 * @since 1.1 - Aug 04, 2011
 * $Id: $
 */

class FunctionCommon{
	/**
     * init
     * - Constructor
     */
    public function __construct() {
    }
	/**
	 * getControllerClass
	 */
	public static function getControllerClass($controller) {
	    $controller .= "_Controller";
	    $controller = explode("_", $controller);
	    $arr = array();
	    foreach ($controller as $_s) {
	        $arr[] = ucfirst($_s);
	    }
	    return ! empty($arr) ? implode("_", $arr) : NULL;
	}
	
	/**
	 * getPost
	 */
	public static function getPost($arrPostField) {
		$aPostValue = array();
		for ($i = 0; $i < count($arrPostField); $i++) {
			if (isset($_POST[$arrPostField[$i]])) {
				if (is_array($_POST[$arrPostField[$i]])) {
					foreach ($_POST[$arrPostField[$i]] as $key=>$value) {
						$aPostValue[$arrPostField[$i]][$key] = trim($value);
					}
				} else {
					$aPostValue[$arrPostField[$i]] = trim($_POST[$arrPostField[$i]]);
				}
			} else {
				$aPostValue[$arrPostField[$i]] = null;
			}
		}
		return $aPostValue;
	}
	
	/**
	 * getGet
	 */
	public static function getGet($arrGetField) {
		$aGetValue = array();
		for ($i = 0; $i < count($arrGetField); $i++) {
			$aGetValue[$arrGetField[$i]] = isset($_GET[$arrGetField[$i]]) ? trim($_GET[$arrGetField[$i]]) : null;
		}
		return $aGetValue;
	}
	
	/**
	 * getImage
	 */
	public static function getImage($type, $imageName) {
		$imageItem = 'noimage.png';
		switch ($type) {
			case 'img-the':
				$folderImg = '/img-the/';
				break;
			case 'img-the-min':
				$folderImg = '/img-the-min/';
				break;
		}
		$path_temp = FOLDER_IMAGE_DIR . $folderImg;
		$img = $path_temp . $imageItem;
		if (is_file(HTDOC_IMAGES_DIR . $folderImg . $imageName)) {
			$img =  $path_temp . $imageName;
		}
		return $img;
	}
	
	/**
	 * uploadFileTo
	 */
	public static function uploadFileTo($arrFile, $_dir, $rmFile) {
		// Kiem tra file co bi error?
		if (is_array($arrFile) && $arrFile['error'] == 0) {
			// Tao ten file moi.
			$nameFile = date("dmY-His") . "-" . $arrFile['name'];
			// Kiem tra kieu file co dc cho phep ko?
			if (FunctionCommon::validateTypeImage($nameFile)) {
				include_once(LIB_CORE_DIR . "/Gdthumb.class.php");
				// Tao doi tuong de convert file moi.
				$imageAt = new Gdthumb();
				$imageAt->load($arrFile["tmp_name"]);
				// Kiem tra co dung la file upload?
				if (is_uploaded_file($arrFile['tmp_name'])) {
					// Tao folder
					$dirName = HTDOC_IMAGES_DIR . "/" . $_dir;
					if (!is_dir($dirName)) {
						mkdir($dirName);
					}
					//chmod($dirName, 0777);
					if (move_uploaded_file ($arrFile['tmp_name'], $dirName . "/" . $nameFile)) {
						// Tao image voi size nho.
						$dirNameMin = HTDOC_IMAGES_DIR . "/" . $_dir . "-min";
						if (!is_dir($dirNameMin)) {
							mkdir($dirNameMin);
						}
						//chmod($dirNameMin, 0777);
						$imageAt->resizeToWidth("100");
						$imageAt->save($dirNameMin . "/" . $nameFile);
						// Remove file
						FunctionCommon::move($dirName . "/" . $rmFile);
						FunctionCommon::move($dirNameMin . "/" . $rmFile);
						return $nameFile;
					} else {
						return false;	
					}
				} else {
					return false;
				}
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
	
	/**
	 * move
	 */
	public static function move($src) {
		if (is_file($src)) {
			unlink($src);
			return true;
		}
		return false;
	}
	
	/**
	 * validateTypeImage
	 */
	public static function validateTypeImage($fileName) {
		if (preg_match('/\.(jpg|jpeg|jpe|jfif|gif|png|swf)$/i', strtolower($fileName))) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * flashHtml
	 */
	public static function flashHtml($url, $width = 100, $height = 100) {
		$html  = "<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0' ";
		$html .= " width='" . $width . "' height='" . $height . "'> ";
		$html .= "<param name='movie' value='" . $url . "' />";
		$html .= "<param name='quality' value='high' />";
		$html .= "<param name='wmode' value='transparent'>";
		$html .= "<embed src='" . $url . "' quality='high' type='application/x-shockwave-flash' width='". $width . "' height='" . $height . "' wmode='transparent' pluginspage='http://www.macromedia.com/go/getflashplayer' />";
		$html .= "</object>";
		return $html;
	}
	
	/**
	 * makeSelectHTML
	 */
	public static function makeSelectHTML($arrValue, $selectName, $valueChoice = "", $addDefault = false, $url = '', $onChage = false) {
        $strSelectHTML = "";      
        if (is_array($arrValue)) {
            $strSelectHTML = "<select name='" . trim($selectName) . "' style='width:390px;'";
            if ($onChage) {
            	$strSelectHTML .= " onchange=\"hrefLocation('".$url."', this.value, '". constants::$pathUrl . "')\"";
            }
            $strSelectHTML .= ">";
            if ($addDefault == false) {
                $strSelectHTML .= "<option value='' selected='selected'>-- --</option>";
            }
            if (!empty($arrValue)) {
                foreach ($arrValue as $key => $value) {
                    $strSelectHTML .= "<option value='" . $key . "'";
                    if (($valueChoice == $key) && ($valueChoice != null)) {
                        $strSelectHTML .= " selected='selected'";
                    }
                    $strSelectHTML .= ">" . $value . "</option>";
                }
            }
            $strSelectHTML .= "</select>";
        }
        return $strSelectHTML;
    }
	
	/**
	 * checkImage
	 */
	public static function checkImage($image) {
	 	$arrFile = explode('.', $image);
	 	if ($arrFile['1'] == 'swf') {
	 		return true;
	 	}
	 	return false;
	 }
	 
	 /**
	 * convertDate
	 */
	 public static function convertDate($datetime, $flag = false) {
	 	$dateTime = explode(" ", $datetime);
	 	$date = $dateTime["0"];
	 	$time = $dateTime["1"];
	 	
	 	$string = substr($date, 0, 10);
	 	$arrStr = explode("-", $string);
	 	$result = "";
	 	if ($flag) {
	 		$result = $arrStr[2] ."-". $arrStr[1] ."-". $arrStr[0] ." ". $time;
	 	} else {
	 		$result = $arrStr[2] ."-". $arrStr[1] ."-". $arrStr[0];
	 	}
	 	return $result;
	 }
	 
	/**
	 * getLanguage
	 */
	 public static function getLanguage() {
	 	$language = Session::Get("LANGUAGE");
	 	if ($language == 'vn') {
	 		return 'vn';
	 	}else {
	 		return 'vn';
	 	}
	 }
	/**
	 * sendRedirect
	*/
	public static function sendRedirect($url = "", $f = true) {
		if ($f) {
    		$url = WEB_LINK . '/' . trim($url);
		}
    	header("Location: " . $url);exit;
    }
    
	/**
	 * sendMail
	*/
	public static function sendMail($arrMail, $sub='Hello', $body='Hello', $type = 'to') {
    	include_once(LIB_THIRD_PARTY_DIR . "/mailer/class.phpmailer.php");
		$mailer = new PHPMailer();
		$mailer->IsSMTP(); // goi class smtp de dang nhap
		$mailer->CharSet="utf-8";
		
		$mailer->SMTPAuth = true; // Dang nhap
		$mailer->SMTPSecure = "ssl"; // Giao thuc SSL
		$mailer->Host = "smtp.gmail.com"; // SMTP của GMAIL
		$mailer->Port = 465; // cong SMTP
		
		$mailer->FromName = 'MuaTheNhanh'; // ten nguoi gui
		$mailer->Username = "tampv9@gmail.com"; // GMAIL username
		$mailer->Password = "28031988l"; // GMAIL password
		if ($type == 'to') {
			foreach ($arrMail as $mail) {
				$mailer->AddAddress($mail['mail'], $mail['name']); //email nguoi nhan
			}
		} elseif ($type == 'cc') {
			foreach ($arrMail as $mail) {
				$mailer->AddCC($mail['mail'], $mail['name']); //email nguoi nhan
			}
		} elseif ($type == 'bcc') {
			foreach ($arrMail as $mail) {
				$mailer->AddBCC($mail['mail'], $mail['name']); //email nguoi nhan
			}
		}
		$mailer->Subject = $sub;
		$mailer->Body = html_entity_decode($body, ENT_QUOTES);
		$mailer->IsHTML(false);
		$result = $mailer->Send();
		if(!$result) { 
			return $mailer->ErrorInfo;
		}
		return $result;
	}
	
	/**
    * showAllErrorMessage
    */
	public static function showAllErrorMessage($errorA = array()) {
		$html = "<fieldset style='border:1px solid #FF0000;background-color:#FFFFCC;font-size:12px;padding: 5px;margin:10px auto;width:90%;text-align:left;'>";
		$html .= "<legend style='color:red;font-size:13px;font-weight:bold;padding-left:5px;text-align:left;'>You have " . count($errorA) ." errors system</legend>";
		$i = 1;
		foreach ($errorA as $ke => $ve) {
			$html .= "<span style='padding-left:20px;font-size:12px;text-align:left;'>" . $i . ". <a class='underError' href='#" . $ke . "'>" . $ve . "</a></span><br>";
			$i++;
		}	
		$html .= "</fieldset>";
		return $html;
	}
	
	/**
    * paging
    */
	public static function paging($ojbPage, $arrParam = null, $arrField = array(), $condition = array(), $orderBy = array()) {
		require_once(LIB_CORE_DIR . "/Paging.class.php");
		$objPaging = new Paging();
	    // Get total record of content menu
		$totalRecord = $ojbPage->getTotalData($condition);
		 // Get page current
        if (isset($_GET["pageNo"])) {
        	$currentPage = $_GET["pageNo"];
        }
        else {
            $currentPage = 1;
        }
		$numberRecord = 10;
        // get page number
		if (!is_null($numberRecord) && $numberRecord != 0) {
			$numberPage = ceil($totalRecord / $numberRecord);
		} else {
			$numberPage = 0;
		}
		// get start record
		$startRecord = ($currentPage - 1) * $numberRecord;

        // get array paging
		$arrPage = $objPaging->getArrPaging($currentPage, $numberPage);
		// get string page
		$strPaging = $objPaging->getStrPaging($arrPage, $currentPage, $numberPage, $arrParam);

        // Get all content menu
        $content = $ojbPage->getListData($startRecord, $numberRecord, $arrField, $condition, $orderBy);
        $no = $startRecord + 1;
		$result = array("total"=>$totalRecord,
						"data"=>$content,
						"currPage"=>$currentPage,
						"numberPage"=>$numberPage,
						"strPaging"=>$strPaging,
						"no"=>$no);

		return $result;
	}
	
	/**
    * writeLogs
    * - write Logs for debug
    * @param String $message
    * @return void
    */
    public static function writeLogs ($message) {
    	if (isset($_GET['oauth_token'])) {
    		$MUser = Session::Get("MUSER");
    	} else {
    		$MUser = Session::Get("MLOGIN");
    	}
    	$module = "unknown";
    	if (isset($_GET['m'])) {
    		$module = $_GET['m'];
    	}
    	$action = "unknown";
    	if (isset($_GET['a'])) {
    		$action = $_GET['a'];
    	}
    	$folder = LOGS_DIR . "/" . date('Ymd');
    	if (!is_dir($folder)) {
    		mkdir($folder);
    		chmod($folder, 0777);
    	}
    	
    	if ($MUser != '') {
    		$name = $MUser['nickname'];
    	} else {
    		$name = "logs";
    	}
    	
    	$fileName = $folder . "/" . $name . ".txt";
		if (is_file($fileName)) {
    		chmod($fileName, 0777);
    	}
        $fp = fopen($fileName, 'a');
        if (!empty($MUser) && is_array($MUser) && $MUser['quyen'] == '0') {
	   		fwrite($fp, "[" . $module . "][" . $action . "][" . date('d H:i:s') . "]  -- admin --\r\n");
        } else {
        	fwrite($fp, "[" . $module . "][" . $action . "][" . date('d H:i:s') . "]  " . $message . "\r\n");
        }
	   	fclose($fp);
    }
}
?>